<template>
  <div class="chat-list-container">
    <el-container>
      <!-- 会话列表 -->
      <el-aside width="300px" class="session-list">
        <div class="session-header">
          <h3>消息</h3>
          <el-button 
            type="primary" 
            size="small" 
            :icon="Search"
            @click="showSearchDialog = true"
            style="margin-top: 10px; width: 100%;"
          >
            搜索用户聊天
          </el-button>
        </div>
        <el-scrollbar class="session-scrollbar">
          <div
            v-for="session in sessionList"
            :key="session.id"
            class="session-item"
            :class="{ active: currentSession?.id === session.id }"
            @click="selectSession(session)"
          >
            <el-avatar :src="session.otherAvatar" :size="45">
              {{ session.otherNickname?.charAt(0) }}
            </el-avatar>
            <div class="session-info">
              <div class="session-name">
                {{ session.otherNickname || session.otherUsername }}
                <el-badge
                  v-if="session.unreadCount > 0"
                  :value="session.unreadCount"
                  class="unread-badge"
                />
              </div>
              <div class="session-last-message">
                {{ session.lastMessage || '暂无消息' }}
              </div>
            </div>
            <div class="session-time">
              {{ formatTime(session.lastMessageTime) }}
            </div>
          </div>
          <el-empty v-if="sessionList.length === 0" description="暂无会话" />
        </el-scrollbar>
      </el-aside>

      <!-- 聊天窗口 -->
      <el-main class="chat-window">
        <div v-if="currentSession" class="chat-content">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <el-avatar :src="currentSession.otherAvatar" :size="40">
              {{ currentSession.otherNickname?.charAt(0) }}
            </el-avatar>
            <span class="chat-username">
              {{ currentSession.otherNickname || currentSession.otherUsername }}
            </span>
          </div>

          <!-- 消息列表 -->
          <el-scrollbar ref="messageScrollbar" class="message-list">
            <div class="message-container">
              <div
                v-for="message in messageList"
                :key="message.id"
                class="message-item"
                :class="{ 'is-self': message.senderId === currentUserId }"
              >
                <el-avatar
                  v-if="message.senderId !== currentUserId"
                  :src="message.senderAvatar"
                  :size="35"
                >
                  {{ message.senderNickname?.charAt(0) }}
                </el-avatar>
                <div class="message-content">
                  <div class="message-bubble">
                    {{ message.content }}
                  </div>
                  <div class="message-time">
                    {{ formatDateTime(message.createTime) }}
                  </div>
                </div>
                <el-avatar
                  v-if="message.senderId === currentUserId"
                  :src="message.senderAvatar"
                  :size="35"
                >
                  {{ message.senderNickname?.charAt(0) }}
                </el-avatar>
              </div>
            </div>
          </el-scrollbar>

          <!-- 消息输入框 -->
          <div class="message-input">
            <el-input
              v-model="messageContent"
              type="textarea"
              :rows="3"
              placeholder="请输入消息..."
              @keydown.enter.ctrl="handleSendMessage"
            />
            <el-button type="primary" @click="handleSendMessage">
              发送 (Ctrl+Enter)
            </el-button>
          </div>
        </div>
        <el-empty v-else description="请选择一个会话开始聊天" />
      </el-main>
    </el-container>

    <!-- 搜索用户对话框 -->
    <el-dialog 
      v-model="showSearchDialog" 
      title="搜索用户" 
      width="500px"
    >
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名或昵称搜索"
        :prefix-icon="Search"
        clearable
        @input="handleSearch"
      />
      <el-scrollbar style="height: 300px; margin-top: 15px;">
        <div
          v-for="user in searchResults"
          :key="user.id"
          class="search-user-item"
          @click="startChatWithUser(user)"
        >
          <el-avatar :src="user.avatar" :size="40">
            {{ user.nickname?.charAt(0) }}
          </el-avatar>
          <div class="user-info">
            <div class="user-name">{{ user.nickname || user.username }}</div>
            <div class="user-username">@{{ user.username }}</div>
          </div>
          <el-button type="primary" size="small">发起聊天</el-button>
        </div>
        <el-empty v-if="searchResults.length === 0 && searchKeyword" description="未找到相关用户" />
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getSessionList, getMessageList, markMessagesAsRead, getOrCreateSession } from '@/api/chat'
import { searchUsers } from '@/api/user'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const currentUserId = computed(() => userStore.userInfo?.id)

// 会话列表
const sessionList = ref([])
const currentSession = ref(null)

// 消息列表
const messageList = ref([])
const messageContent = ref('')
const messageScrollbar = ref(null)

// 分页
const currentPage = ref(1)
const pageSize = ref(50)

// WebSocket连接
let websocket = null

// 搜索相关
const showSearchDialog = ref(false)
const searchKeyword = ref('')
const searchResults = ref([])
let searchTimer = null

// 加载会话列表
const loadSessionList = async () => {
  try {
    const res = await getSessionList()
    sessionList.value = res.data
  } catch (error) {
    ElMessage.error('加载会话列表失败')
  }
}

// 选择会话
const selectSession = async (session) => {
  currentSession.value = session
  currentPage.value = 1
  await loadMessageList()
  
  // 标记消息为已读
  if (session.unreadCount > 0) {
    await markMessagesAsRead(session.id)
    session.unreadCount = 0
  }
}

// 加载消息列表
const loadMessageList = async () => {
  if (!currentSession.value) return

  try {
    const res = await getMessageList({
      sessionId: currentSession.value.id,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    messageList.value = res.data.records.reverse()
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    ElMessage.error('加载消息列表失败')
  }
}

// 发送消息
const handleSendMessage = () => {
  if (!messageContent.value.trim()) {
    ElMessage.warning('消息内容不能为空')
    return
  }

  if (!currentSession.value) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  if (websocket && websocket.readyState === WebSocket.OPEN) {
    const message = {
      type: 'message',
      receiverId: currentSession.value.otherUserId,
      content: messageContent.value,
      messageType: 1
    }
    websocket.send(JSON.stringify(message))
    messageContent.value = ''
  } else {
    ElMessage.error('WebSocket连接未建立')
  }
}

// 初始化WebSocket
const initWebSocket = () => {
  const token = localStorage.getItem('token')
  const wsUrl = `ws://localhost:8080/ws/chat?token=${token}`
  
  websocket = new WebSocket(wsUrl)

  websocket.onopen = () => {
    console.log('WebSocket连接已建立')
  }

  websocket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      if (data.type === 'message') {
        const message = data.data
        
        // 如果是当前会话的消息，添加到消息列表
        if (currentSession.value && 
            (message.senderId === currentSession.value.otherUserId || 
             message.receiverId === currentSession.value.otherUserId)) {
          messageList.value.push(message)
          nextTick(() => scrollToBottom())
          
          // 如果是接收到的消息，标记为已读
          if (message.receiverId === currentUserId.value) {
            markMessagesAsRead(currentSession.value.id)
          }
        }
        
        // 更新会话列表
        loadSessionList()
      } else if (data.type === 'error') {
        ElMessage.error(data.message)
      }
    } catch (error) {
      console.error('处理WebSocket消息失败', error)
    }
  }

  websocket.onerror = (error) => {
    console.error('WebSocket错误', error)
    ElMessage.error('WebSocket连接错误')
  }

  websocket.onclose = () => {
    console.log('WebSocket连接已关闭')
    // 尝试重连
    setTimeout(() => {
      if (websocket.readyState === WebSocket.CLOSED) {
        initWebSocket()
      }
    }, 3000)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageScrollbar.value) {
    const scrollElement = messageScrollbar.value.$el.querySelector('.el-scrollbar__wrap')
    scrollElement.scrollTop = scrollElement.scrollHeight
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }
}

const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 搜索用户
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  searchTimer = setTimeout(async () => {
    try {
      const res = await searchUsers({ keyword: searchKeyword.value })
      searchResults.value = res.data.filter(user => user.id !== currentUserId.value)
    } catch (error) {
      ElMessage.error('搜索用户失败')
    }
  }, 500)
}

// 与用户发起聊天
const startChatWithUser = async (user) => {
  try {
    const res = await getOrCreateSession(user.id)
    showSearchDialog.value = false
    searchKeyword.value = ''
    searchResults.value = []
    
    // 重新加载会话列表
    await loadSessionList()
    
    // 查找并选择该会话
    const session = sessionList.value.find(s => s.otherUserId === user.id)
    if (session) {
      await selectSession(session)
    }
    
    ElMessage.success('已打开聊天窗口')
  } catch (error) {
    ElMessage.error('打开聊天窗口失败')
  }
}

onMounted(() => {
  loadSessionList()
  initWebSocket()
})

onUnmounted(() => {
  if (websocket) {
    websocket.close()
  }
})
</script>

<style scoped>
.chat-list-container {
  height: calc(100vh - 120px);
  background: var(--el-bg-color);
  border-radius: 8px;
  overflow: hidden;
  transition: background-color 0.3s;
}

.el-container {
  height: 100%;
}

/* 会话列表样式 */
.session-list {
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
}

.session-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--el-border-color);
}

.session-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.session-scrollbar {
  flex: 1;
  height: 0;
}

.session-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid var(--el-border-color-lighter);
  position: relative;
}

.session-item:hover {
  background-color: var(--el-fill-color-light);
}

.session-item.active {
  background-color: var(--el-color-primary-light-9);
}

.session-info {
  flex: 1;
  margin-left: 12px;
  overflow: hidden;
}

.session-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.unread-badge {
  margin-left: 8px;
}

.session-last-message {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-time {
  font-size: 11px;
  color: var(--el-text-color-placeholder);
  position: absolute;
  right: 15px;
  top: 15px;
}

/* 聊天窗口样式 */
.chat-window {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.chat-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  background: var(--el-bg-color);
}

.chat-username {
  margin-left: 12px;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.message-list {
  flex: 1;
  height: 0;
  padding: 20px;
}

.message-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
  justify-content: flex-start;
}

.message-item.is-self {
  justify-content: flex-end;
}

.message-content {
  max-width: 60%;
  display: flex;
  flex-direction: column;
}

.message-item.is-self .message-content {
  align-items: flex-end;
}

.message-bubble {
  padding: 10px 15px;
  border-radius: 8px;
  background-color: var(--el-fill-color);
  word-wrap: break-word;
  word-break: break-all;
  color: var(--el-text-color-primary);
}

.message-item.is-self .message-bubble {
  background-color: var(--el-color-primary);
  color: #fff;
}

.message-time {
  font-size: 11px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.message-input {
  padding: 15px 20px;
  border-top: 1px solid var(--el-border-color);
  display: flex;
  gap: 10px;
  align-items: flex-end;
  background: var(--el-bg-color);
}

.message-input .el-input {
  flex: 1;
}

/* 搜索用户样式 */
.search-user-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 8px;
  margin-bottom: 8px;
}

.search-user-item:hover {
  background-color: var(--el-fill-color-light);
}

.search-user-item .user-info {
  flex: 1;
  margin-left: 12px;
}

.search-user-item .user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.search-user-item .user-username {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>

